package com.example.workapp;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class BluetoothActivity extends AppCompatActivity {

    private static final int REQUEST_PERMISSION = 100;
    private static final int REQUEST_ENABLE_BT = 2;
    private BluetoothAdapter bluetoothAdapter;
    private String bluetoothAddress;
    private Uri filePath;
    private ProgressBar progressBar;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private BroadcastReceiver pairingReceiver;
    private BroadcastReceiver connectionReceiver;
    private BluetoothDevice targetDevice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);
        Log.d("BluetoothActivity", "onCreate called");

        progressBar = findViewById(R.id.progressBar);
        progressBar.setMax(100);

        // Initialize Bluetooth adapter
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // Get params from intent
        bluetoothAddress = getIntent().getStringExtra("bluetoothAddress");
        filePath = getIntent().getParcelableExtra("FILE_PATH");

        // Check if necessary params are present
        if (bluetoothAddress == null || filePath == null) {
            Toast.makeText(this, "Missing Bluetooth address or file path", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // Request necessary permissions
        requestBluetoothPermissions();
    }



    private void requestBluetoothPermissions() {
        List<String> permissionsToRequest = new ArrayList<>();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 12+ (API 31+) 需要新的蓝牙权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH_CONNECT);
                Log.d("BluetoothServer", "BLUETOOTH_CONNECT");
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH_SCAN);
                Log.d("BluetoothServer", "BLUETOOTH_SCAN");
            }
        } else {
            // Android 11 及以下 (API ≤ 30) 需要旧的蓝牙权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH_ADMIN);
            }
        }

//        // Android 10 (API 29) 及以上的存储权限
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // Android 13+
//            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES)
//                    != PackageManager.PERMISSION_GRANTED) {
//                permissionsToRequest.add(Manifest.permission.READ_MEDIA_IMAGES);
//            }
//            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_VIDEO)
//                    != PackageManager.PERMISSION_GRANTED) {
//                permissionsToRequest.add(Manifest.permission.READ_MEDIA_VIDEO);
//            }
//        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // Android 10-12
//            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
//                    != PackageManager.PERMISSION_GRANTED) {
//                permissionsToRequest.add(Manifest.permission.READ_EXTERNAL_STORAGE);
//            }
//        } else { // Android 9 及以下
//            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                    != PackageManager.PERMISSION_GRANTED) {
//                permissionsToRequest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//            }
//        }

        // 如果有未授予的权限，则请求
        if (!permissionsToRequest.isEmpty()) {
            ActivityCompat.requestPermissions(
                    this,
                    permissionsToRequest.toArray(new String[0]),
                    REQUEST_PERMISSION
            );
        } else {
            // 所有权限已授予，执行蓝牙传输
            setupBluetoothTransfer();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_PERMISSION) {
            boolean allPermissionsGranted = true;

            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }

            if (allPermissionsGranted) {
                setupBluetoothTransfer();
            } else {

                showPermissionDeniedDialog();
            }
        }
    }


    private void showPermissionDeniedDialog() {
        new AlertDialog.Builder(this)
                .setTitle("权限需要")
                .setMessage("Bluetooth and storage permissions are required for file transfer.")
                .setPositiveButton("Open Settings", (dialog, which) -> {
                    Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                    finish();
                })
                .setNegativeButton("Exit", (dialog, which) -> finish())
                .setCancelable(false)
                .show();
    }

    @SuppressLint("MissingPermission")
    private void setupBluetoothTransfer() {
        // Check if Bluetooth is enabled
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            return;
        }

        // Initialize Bluetooth device
        targetDevice = bluetoothAdapter.getRemoteDevice(bluetoothAddress);

        // Register Bluetooth receivers
        registerPairingReceiver();
        registerConnectionReceiver();

        // Initiate pairing or file transfer
        initiatePairing();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_OK) {
                // Bluetooth is now enabled, proceed with setup
                setupBluetoothTransfer();
            } else {
                Toast.makeText(this, "Bluetooth must be enabled for file transfer", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
    private void registerPairingReceiver() {
        pairingReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                //监听请求匹配
                if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    showPairingConfirmationDialog(device);
                }
            }
        };

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
        registerReceiver(pairingReceiver, filter);
    }

    private void showPairingConfirmationDialog(BluetoothDevice device) {
        new AlertDialog.Builder(this)
                .setTitle("蓝牙配对请求")
                .setMessage("是否允许设备 " + device.getName() + " 配对？")
                .setPositiveButton("允许", (dialog, which) -> {
                    try {
                        device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                })
                .setNegativeButton("拒绝", (dialog, which) -> {
                    try {
                        device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device, true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                })
                .show();
    }


    private void registerConnectionReceiver() {
        connectionReceiver = new BroadcastReceiver() {
            //有匹配请求
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                    int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE);
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                    switch (bondState) {
                        case BluetoothDevice.BOND_BONDED:
                            // 配对成功，准备接收文件
                            Log.d("BluetoothServer", "与设备 " + device.getName() + " 配对成功");
                            attemptConnection(targetDevice);
                            break;
                        case BluetoothDevice.BOND_BONDING:
                            Log.d("BluetoothServer", "正在与设备 " + device.getName() + " 配对");
                            break;
                        case BluetoothDevice.BOND_NONE:
                            Log.d("BluetoothServer", "与设备 " + device.getName() + " 配对失败");
                            break;
                    }
                }
            }
        };

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(connectionReceiver, filter);
    }

    private void initiatePairing() {
        // 检查目标设备是否已经配对
        if (targetDevice.getBondState() == BluetoothDevice.BOND_NONE) {
            // 如果未配对，则创建配对
            boolean isBondingStarted = targetDevice.createBond();
            if (!isBondingStarted) {
//                Toast.makeText(this, "配对请求失败，请重试", Toast.LENGTH_SHORT).show();
                retryPairing();
            }
        } else {
            // 如果已配对，直接进行文件传输
            runOnUiThread(() -> progressBar.setVisibility(View.VISIBLE));
            attemptConnection(targetDevice);
        }
    }

    private void retryPairing() {
        new Handler().postDelayed(() -> {
            if (targetDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                initiatePairing();
            }
        }, 5000); // 5秒后重试
    }



    private void attemptConnection(BluetoothDevice device) {
        new Thread(() -> {
            int attempts = 0;
            while (attempts < 3) {
                BluetoothSocket socket = null;
                try {
                    Log.d("BluetoothActivity", "尝试连接蓝牙设备: 第" + (attempts + 1) + "次");
                    socket = device.createRfcommSocketToServiceRecord(MY_UUID);
                    socket.connect();

                    // 连接成功，更新 UI 并传输文件
                    runOnUiThread(() -> {
                        Toast.makeText(this, "蓝牙连接成功", Toast.LENGTH_SHORT).show();
                        progressBar.setVisibility(View.VISIBLE);
                    });
                    sendFile(socket);
                    return; // 连接成功，退出重试循环
                } catch (IOException e) {
                    Log.e("BluetoothActivity", "蓝牙连接尝试失败: " + (attempts + 1), e);
                    attempts++;

                    if (socket != null) {
                        try {
                            socket.close();
                        } catch (IOException closeException) {
                            Log.e("BluetoothActivity", "关闭socket失败", closeException);
                        }
                    }

                    try {
                        Thread.sleep(2000); // 休息2秒再尝试
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }
            }

            // 所有尝试都失败
            runOnUiThread(() -> {
                Toast.makeText(this, "多次连接尝试均失败", Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.GONE);
            });
        }).start();
    }

    /**
     * 文件传输逻辑（运行在子线程）
     */
    private void sendFile(BluetoothSocket bluetoothSocket) {
        OutputStream outputStream = null;
        InputStream inputStream = null;
        FileInputStream fileInputStream = null;

        try {
            // 获取输出流
            outputStream = bluetoothSocket.getOutputStream();

            // 获取文件输入流
            fileInputStream = (FileInputStream) getContentResolver().openInputStream(filePath);

            // 获取蓝牙输入流（用于接收确认信号）
            inputStream = bluetoothSocket.getInputStream();

            // 发送 MIME 类型
            String mimeType = getContentResolver().getType(filePath);
            if (mimeType == null) {
                mimeType = "application/octet-stream"; // 默认 MIME 类型
            }

            byte[] mimeTypeBytes = mimeType.getBytes(StandardCharsets.UTF_8);
            outputStream.write(intToBytes(mimeTypeBytes.length)); // 先发送 MIME 类型的长度
            outputStream.write(mimeTypeBytes); // 再发送 MIME 类型的内容
            outputStream.flush();

            // 获取文件大小
            ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(filePath, "r");
            long fileSize = (pfd != null) ? pfd.getStatSize() : -1;

            // 发送文件大小
            outputStream.write(longToBytes(fileSize));
            outputStream.flush();

            Log.d("BluetoothActivity", "准备发送文件，大小: " + fileSize + " 字节");

            // 更新进度条最大值
            runOnUiThread(() -> progressBar.setVisibility(View.VISIBLE));

            // 发送文件内容
            byte[] buffer = new byte[1024];
            int bytesRead;
            long totalBytesRead = 0;

            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                if (bluetoothSocket.isConnected()) {
                    outputStream.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;

                    // 每次发送后刷新缓冲区
                    outputStream.flush();
                    // 计算进度并更新 UI
                    final int progress = (fileSize > 0) ? (int) ((totalBytesRead * 100) / fileSize) : 0;
                    runOnUiThread(() -> progressBar.setProgress(progress));

                    // 记录传输进度
                    if (fileSize > 10 && (totalBytesRead % Math.max(1, fileSize / 10)) < 1024) {
                        Log.d("BluetoothActivity", "文件传输进度: " + progress + "%");
                    }
                } else {
                    throw new IOException("蓝牙连接已断开");
                }
            }

            Log.d("BluetoothActivity", "文件发送完成，等待确认");

            // 等待client端的确认信号
            byte[] ackBuffer = new byte[1];
            int ackBytesRead = inputStream.read(ackBuffer);

            if (ackBytesRead == 1 && ackBuffer[0] == 1) {
                Log.d("BluetoothActivity", "接收到文件传输确认信号");
                runOnUiThread(() -> {
                    Toast.makeText(BluetoothActivity.this, "文件发送成功！", Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.GONE);
                    runOnUiThread(() -> showFileSendedDialog());
                });
            } else {
                throw new IOException("未收到接收方确认信号");
            }

        } catch (SecurityException e) {
            Log.e("BluetoothActivity", "SecurityException: " + e.getMessage());
            runOnUiThread(() -> {
                Toast.makeText(BluetoothActivity.this, "权限错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.GONE);
            });
        } catch (IllegalArgumentException e) {
            Log.e("BluetoothActivity", "IllegalArgumentException: " + e.getMessage());
            runOnUiThread(() -> {
                Toast.makeText(BluetoothActivity.this, "参数错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.GONE);
            });
        } catch (IOException e) {
            Log.e("BluetoothActivity", "IOException: " + e.getMessage());
            runOnUiThread(() -> {
                Toast.makeText(BluetoothActivity.this, "传输错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.GONE);
            });
        } catch (Exception e) {
            Log.e("BluetoothActivity", "Unknown exception: " + e.getMessage());
            runOnUiThread(() -> {
                Toast.makeText(BluetoothActivity.this, "未知错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.GONE);
            });
        } finally {
            // 关闭所有流
            try {
                if (fileInputStream != null) fileInputStream.close();
                if (outputStream != null) outputStream.close();
                if (inputStream != null) inputStream.close();
                if (bluetoothSocket != null && bluetoothSocket.isConnected()) {
                    bluetoothSocket.close();
                }
            } catch (IOException e) {
                Log.e("BluetoothActivity", "关闭资源时发生错误: " + e.getMessage());
            }
        }
    }

    private void showFileSendedDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("文件发送成功");

        // 点击确认
        builder.setPositiveButton("确认", (dialog, which) -> {
            dialog.dismiss(); // 关闭弹窗
            finish(); // 关闭当前 Activity
        });

        // 显示弹窗
        builder.create().show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消注册广播接收器
        if (pairingReceiver != null) {
            unregisterReceiver(pairingReceiver);
        }
        if (connectionReceiver != null) {
            unregisterReceiver(connectionReceiver);
        }
    }

    // 将long类型转换为byte数组
    private byte[] longToBytes(long value) {
        byte[] result = new byte[8];
        for (int i = 7; i >= 0; i--) {
            result[i] = (byte) (value & 0xFF);
            value >>= 8;
        }
        return result;
    }

    private static byte[] intToBytes(int value) {
        return new byte[]{
                (byte) (value >> 24), // 最高位字节
                (byte) (value >> 16), // 次高位字节
                (byte) (value >> 8),  // 次低位字节
                (byte) value          // 最低位字节
        };
    }
}